package com.F03.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.F03.actionform.F0302ActionForm;
import com.F03.dao.PdPlanningDAO;
import com.F03.info.PdPlanningInfo;
import com.action.BaseAction;
import com.config.Constants;
import com.exception.SelectException;
import com.info.T_S_YHCZXXinfo;
import com.util.CommonTools;
import com.util.SessionUtils;

/**
 * 
 * @file F0302Action.java
 * @author huqy
 * @since 2009-3-15
 * @version 1.0
 */
public class F0302Action extends BaseAction {

	/**
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	Logger log = Logger.getLogger(F0302Action.class);

	/** 操作记录INFO */
	T_S_YHCZXXinfo t_YhczxxInfo = null;
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		F0302ActionForm actionForm = (F0302ActionForm) form;
		PdPlanningDAO dao = new PdPlanningDAO();
		PdPlanningInfo info = new PdPlanningInfo();
		String operationType = actionForm.getOperationType();
		String strQuery = "query";
		String strQueryAdvance = "queryAdvance";
		String strDetail="detail";
		String strList = "list";
		String language = SessionUtils.getLocale(request);
		actionForm.setLanguage(language);
		try {
			//操作记录
			t_YhczxxInfo = setYhczxx(request, response, operationType,"F0302");
			if(Constants.ADD.equals(operationType)){
				doAdd(actionForm,dao);
				//log.info(mapping.findForward(strDetail).getPath());
				return mapping.findForward(strDetail);	
			}
			
			if(Constants.SAVE_INSERT.equals(operationType)){
				if(doInsert(actionForm,dao)){	
					String url=mapping.findForward("doList").getPath();
		            ActionForward forward=new ActionForward(url+"?operationType=queryList&errorFlag="+actionForm.getErrorFlag());
		    		return forward;
				}else{
					return mapping.findForward("detail");					
				}
			}
			
			if(Constants.SAVE_UPDATE.equals(operationType)){
				if(doUpdate(actionForm,dao)){				
					String url=mapping.findForward("doList").getPath();
		            ActionForward forward=new ActionForward(url+"?operationType=queryList&errorFlag="+actionForm.getErrorFlag());
		    		return forward;
				}else{
					return mapping.findForward("detail");		
				}
			}
			
			if(Constants.EDIT.equals(operationType)){
				doEdit(actionForm,dao);
                return mapping.findForward("detail");
			}
		
			if(Constants.DELETE.equals(operationType)){
				if(doDelete(actionForm,dao)){				
					String url=mapping.findForward("doList").getPath();
		            ActionForward forward=new ActionForward(url+"?operationType=queryList");
		    		return forward;
				}else{
					return mapping.findForward("list");		
				}
			}
			/*
			if(Constants.BACK.equals(operationType)){
				return mapping.findForward(strList);
			}
			*/
			if(strQuery.equals(operationType)){
				
				initQuery(actionForm,dao,request,response);
				return mapping.findForward(strDetail);
			}
			if(strQueryAdvance.equals(operationType)){
				initPreviousAdvance(actionForm,dao,request,response);
				return mapping.findForward(strDetail);
			}
			if(Constants.QUERYLIST.equals(operationType)){
				info.setManufacturingOrder1(CommonTools.null2String(actionForm.getManufacturingOrder1()));
				info.setManufacturingOrder2(CommonTools.null2String(actionForm.getManufacturingOrder2()));
				//actionForm.setList(dao.queryList(info));
				doQueryList(actionForm,dao.queryList(info));
				return mapping.findForward(strList);
			}
			
			if(Constants.INIT.equals(operationType)){
				return mapping.findForward(strList);
			}
			
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			if (dao != null) dao.disConnect();
		}
		return mapping.findForward(strList);
	}
	
	private void doQueryList(F0302ActionForm actionForm,List list){
		if(list!=null&&list.size()>0){
			actionForm.setList(list);
		}
		else{
			actionForm.setList(list);
			actionForm.setErrorFlag("2");
		}	
	}
	
	private void  doEdit(F0302ActionForm actionForm,PdPlanningDAO dao) throws SelectException{
		try {
			
		    Map map = null;
		    List list = new ArrayList();
			list = dao.selectById(actionForm.getId());
			 for(int i = 0; i < list.size();i++){
				map = (Map)list.get(i);	

				actionForm.setId(CommonTools.null2String((String)map.get("ID")));
				actionForm.setManufacturingOrder(CommonTools.null2String((String)map.get("MANUFACTURINGORDER")));
				actionForm.setGroups(CommonTools.null2String((String)map.get("GROUPS")));
				actionForm.setGroupQty(CommonTools.null2String((String)map.get("GROUPQTY")));
				actionForm.setPreviousAdvance(CommonTools.null2String((String)map.get("PREVIOUSADVANCE")));
				actionForm.setLastAdvance(CommonTools.null2String((String)map.get("LASTADVANCE")));
				actionForm.setLastAdvanceDate(CommonTools.null2String((String)map.get("LASTADVANCEDATE")));
				actionForm.setManufacturingQty(CommonTools.null2String((String)map.get("MANUFACTURINGQTY")));
				actionForm.setLayOutType("");
				actionForm.setGroupsList(dao.getGroupsListOther(actionForm.getManufacturingOrder()));
				actionForm.setPreviousAdvanceList(dao.getPreviousAdvanceList(actionForm.getManufacturingOrder()));
				actionForm.setLastAdvanceList(dao.getPreviousAdvanceList(actionForm.getManufacturingOrder()));
				actionForm.setModelName(dao.getModelName(actionForm.getManufacturingOrder()));
				//actionForm.setCollectionList(dao.getCollectionList());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
	private void getFormOther(String id,PdPlanningDAO dao,F0302ActionForm actionForm) throws SelectException{
		try {
		    Map map = null;
		    List list = new ArrayList();
			list = dao.selectById(id);
			 for(int i = 0; i < list.size();i++){
				map = (Map)list.get(i);	
				actionForm.setId(CommonTools.null2String((String)map.get("ID")));
				actionForm.setManufacturingOrder(CommonTools.null2String((String)map.get("MANUFACTURINGORDER")));
				actionForm.setGroups(CommonTools.null2String((String)map.get("GROUPS")));
				actionForm.setGroupQty(CommonTools.null2String((String)map.get("GROUPQTY")));
				actionForm.setPreviousAdvance(CommonTools.null2String((String)map.get("PREVIOUSADVANCE")));
				actionForm.setLastAdvance(CommonTools.null2String((String)map.get("LASTADVANCE")));
				actionForm.setLastAdvanceDate(CommonTools.null2String((String)map.get("LASTADVANCEDATE")));
				actionForm.setManufacturingQty(CommonTools.null2String((String)map.get("MANUFACTURINGQTY")));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
	private boolean doDelete(F0302ActionForm actionForm,PdPlanningDAO dao){
		boolean flag=false;
		try {
			String id=CommonTools.null2String(actionForm.getId());
			getFormOther(id,dao,actionForm);
			flag=dao.delete(id, actionForm);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	private void initPreviousAdvance(F0302ActionForm actionForm,PdPlanningDAO dao,HttpServletRequest request, HttpServletResponse response){
		
		String responseXML = "";
		try{
			response.setContentType("text/xml");
			//response.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("GBK");
			PrintWriter out = response.getWriter();
			
			responseXML = dao.getPhasesCode(actionForm.getManufacturingOrder(), actionForm.getGroups());
			out.write(responseXML);
			out.flush();
			out.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	//利用ajax 初始化F0302Detail.jsp 页面 
	private void initQuery(F0302ActionForm actionForm,PdPlanningDAO dao,HttpServletRequest request, HttpServletResponse response){
		StringBuffer responseXML = new StringBuffer();
		String[] columnsGroups = null;
		String[] columnsAdvances = null;
		List groupsList = null;
		List advancesList = null;
		Map map = null;
		String modelName = "";
		try{
			response.setContentType("text/xml");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			
			columnsGroups = new String[]{"CODE","NAME"};
			columnsAdvances = new String[]{"CODE1","NAME1"};
			groupsList = dao.getGroupsList(actionForm.getManufacturingOrder());
			advancesList = dao.getPreviousAdvanceList(actionForm.getManufacturingOrder());
			modelName = dao.getModelName(actionForm.getManufacturingOrder());
			
			responseXML.append("<INFOS>\n");
			for(int i = 0; i < groupsList.size(); i++){

				responseXML.append("<GROUP>\n");
				map = (Map)groupsList.get(i);
				for(int j = 0; j < columnsGroups.length; j++){

					responseXML.append("<").append(columnsGroups[j]).append(">");
					responseXML.append((String)map.get(columnsGroups[j]));
					responseXML.append("</").append(columnsGroups[j]).append(">\n");
				}
				
				responseXML.append("</GROUP>\n");
              
			}
			for(int i=0;i<advancesList.size();i++){
				responseXML.append("<ADVANCE>\n");
				map = (Map)advancesList.get(i);
				for(int j = 0; j < columnsAdvances.length; j++){

					responseXML.append("<").append(columnsAdvances[j]).append(">");
					responseXML.append((String)map.get(columnsAdvances[j]));
					responseXML.append("</").append(columnsAdvances[j]).append(">\n");
				}

				responseXML.append("</ADVANCE>\n");
			}
			if(!modelName.equals("")){
				responseXML.append("<MODEL>\n");
				   responseXML.append("<NAME>\n");
				      responseXML.append(modelName);
				   responseXML.append("</NAME>\n");
				responseXML.append("</MODEL>\n");
			}
			
			responseXML.append("</INFOS>\n");
			
			out.write(responseXML.toString());
			out.flush();
			out.close();
			
		}catch (Exception e){
			e.printStackTrace();
		}
		
	}
	
	private void doAdd(F0302ActionForm actionForm,PdPlanningDAO dao){
		try {
			
			actionForm.setLayOutType("add");
			actionForm.setId("");
			actionForm.setManufacturingOrder("");
			actionForm.setModel("");
			actionForm.setGroupQty("");
			actionForm.setLastAdvanceDate("");
			actionForm.setModelName("");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private boolean doInsert(F0302ActionForm actionForm,PdPlanningDAO dao){
		boolean flag=false;
		PdPlanningInfo info=new PdPlanningInfo();
		try {
	
			if(!CommonTools.isNullString(actionForm.getGroups())){
				info.setGroups(actionForm.getGroups().split("\\*")[0]);
			}else{
				return flag;
			}
			info.setManufacturingOrder(CommonTools.null2String(actionForm.getManufacturingOrder()));
			info.setPreviousAdvance(CommonTools.null2String(actionForm.getPreviousAdvance()));
			info.setGroupQty(CommonTools.null2String(actionForm.getGroupQty()));
			info.setLastAdvance(CommonTools.null2String(actionForm.getLastAdvance()));
			info.setLastAdvanceDate(CommonTools.null2String(actionForm.getLastAdvanceDate()));
			flag=dao.insert(info,actionForm);	
			
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return flag;
	}
	
	private boolean doUpdate(F0302ActionForm form,PdPlanningDAO dao){
		boolean flag=false;
		try {
			form.setErrorFlag("");
			PdPlanningInfo info=new PdPlanningInfo();
			info.setId(CommonTools.null2String(form.getId()));
			info.setManufacturingOrder(CommonTools.null2String(form.getManufacturingOrder()));
			info.setPreviousAdvance(CommonTools.null2String(form.getPreviousAdvance()));
			info.setGroups(CommonTools.null2String(form.getGroups().split("\\*")[0]));
			info.setGroupQty(CommonTools.null2String(form.getGroupQty()));
			info.setLastAdvance(CommonTools.null2String(form.getLastAdvance()));
			info.setLastAdvanceDate(CommonTools.null2String(form.getLastAdvanceDate()));
			flag=dao.update(info,form);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;	
	}
	
}
